package com.xxl.job.executor.service.jobhandler;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.mybatis.entity.JobUser;
import com.xxl.job.executor.mybatis.service.JobUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.xxl.job.core.handler.IJobHandler.SUCCESS;


/**
 * @author: 吴多强
 * @description: 分片批量查询
 */
@Component
public class ShardingBatchSelect {
    private static Logger logger = LoggerFactory.getLogger(ShardingBatchSelect.class);
    @Resource
    private JobUserService jobUserService;

    @XxlJob("ShardingBatchSelect")
    public ReturnT<String> shardingJobHandler(String param) throws Exception {
        // 当前分片序号
        int index = XxlJobContext.getXxlJobContext().getShardIndex() + 1;
        // 总分片数
        int total = XxlJobContext.getXxlJobContext().getShardTotal();
        // 总的分片任务
        int all = Integer.parseInt(param);
        // 平均分片个数
        int avg = all / total;
        logger.info("当前分片序号" + index + " 总分片数" + total + "总的分片任务" + all + "平均分片个数" + avg);
        selectJobUser(index, avg, jobUserService);
        return SUCCESS;
    }

    static void selectJobUser(int index, int avg, JobUserService jobUserService) {
        Page<JobUser> jobUserPage = new Page<>();
        jobUserPage.setCurrent(index);
        jobUserPage.setSize(avg);
        long startTime = System.currentTimeMillis() / 1000;
        jobUserService.page(jobUserPage);
        long endTime = System.currentTimeMillis() / 1000;
        logger.info("耗时" + (endTime - startTime) + "秒");
    }
}
